package com.shujia.dws

import com.shujia.common.SparkTool
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.{DataFrame, SaveMode, SparkSession}

object DwsCityTouristMskDay extends SparkTool {
  override def run(spark: SparkSession): Unit = {
    import spark.implicits._
    import org.apache.spark.sql.functions._

    // 加载位置数据融合表、行政区域配置表、用户画像表
    val mergeDF: DataFrame = spark.table("dwi.dwi_res_regn_mergelocation_msk_d").where($"day_id" === day_id)
    val adminCodeDF: DataFrame = spark.table("dim.dim_admincode").select($"county_id", $"city_id")
    val userTagDF: DataFrame = spark.table("dim.dim_usertag_msk_d").where($"day_id" === day_id)
      .select($"mdn", $"resi_grid_id", $"resi_county_id")

    // 先将位置数据融合表和行政区域配置表关联，将区县ID转换成城市ID
    mergeDF
      .join(adminCodeDF, List("county_id"), "inner")
      // 计算停留时间
      .withColumn("min_start_time", min($"start_date") over Window.partitionBy($"mdn", $"city_id"))
      .withColumn("max_end_time", min($"end_date") over Window.partitionBy($"mdn", $"city_id"))
      .withColumn("d_stay_time", unix_timestamp($"max_end_time", "yyyyMMddHHmmss") - unix_timestamp($"min_start_time", "yyyyMMddHHmmss"))
      .where($"d_stay_time" > 3 * 60 * 60)
      // 关联用户画像数据，通过网格id计算出行距离
      .join(userTagDF, List("mdn"), "inner")
      // 计算每个用户从每个居住地到每个网格的距离
      .withColumn("distance", calLengthWithGrid($"resi_grid_id", $"grid_id"))
      .withColumn("d_max_distance", max($"distance") over Window.partitionBy($"mdn", $"resi_grid_id", $"city_id"))
      .where($"d_max_distance" > 100 * 1000)
      // 整理数据
      .select(
        $"mdn"
        , $"resi_county_id" as "source_county_id"
        , $"city_id" as "d_city_id"
        , $"d_stay_time"
        , $"d_max_distance"
      )
      .distinct()
      .write
      .format("csv")
      .option("sep", ",")
      .mode(SaveMode.Overwrite)
      .save(s"/daas/motl/dws/dws_city_tourist_msk_d/day_id=$day_id")

    // 增加分区
    spark.sql(
      s"""
         |alter table dws.dws_city_tourist_msk_d add if not exists partition(day_id=$day_id)
         |""".stripMargin)

  }
}
